#import "ToDoView.h"

@implementation ToDoView

- (id)initWithFrame:(struct CGRect)frame
{
	self = [super initWithFrame:frame];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(reloadTableData)
												 name:@"ToDoDidChangeNotification"
											   object:nil];

	
	toDoManager = [ToDoManager sharedToDoManager];
	td = [MobileToDoListApplication sharedInstance];
	
	editMode = NO;
	imageHeight = 23;
	rowHeight = 40;
	swapAddButton = YES;
	
	if([[toDoManager getPref:@"rowHeight"] intValue] > 0) {
		rowHeight = [[toDoManager getPref:@"rowHeight"] intValue];
	}
	swapAddButton = [[toDoManager getPref:@"swapAddButton"] intValue];

	checkboxOn 	= [UIImage applicationImageNamed:@"checkbox_on.png"];
	checkboxOff = [UIImage applicationImageNamed:@"checkbox_off.png"];
	
	icon1 	= [UIImage applicationImageNamed:@"1.png"];
	icon2 	= [UIImage applicationImageNamed:@"2.png"];
	icon3 	= [UIImage applicationImageNamed:@"3.png"];
	icon4 	= [UIImage applicationImageNamed:@"4.png"];
	icon5 	= [UIImage applicationImageNamed:@"5.png"];
	icon6 	= [UIImage applicationImageNamed:@"6.png"];
	icon7 	= [UIImage applicationImageNamed:@"7.png"];
	icon8 	= [UIImage applicationImageNamed:@"8.png"];
	icon9 	= [UIImage applicationImageNamed:@"9.png"];
	
	
	//Get full screen app rect
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	navBar = [[UINavigationBar alloc] init];
	[navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 45.0f)];
	[navBar showLeftButton:@"Edit" withStyle:0 rightButton:@" + " withStyle:0];

	
	[navBar setDelegate:self];
	[navBar enableAnimation];
	
	bottomNavBar = [[UINavigationBar alloc] init];
	[bottomNavBar setFrame:CGRectMake(rect.origin.x, 415.0f, rect.size.width, 45.0f)];
	[bottomNavBar showLeftButton:@"Preferences" withStyle:0 rightButton:nil withStyle:0];
	[bottomNavBar setDelegate:self];
	[bottomNavBar enableAnimation];
	
	
	
	
	
	[self buildTable];
	[self addSubview:bottomNavBar];
	[self addSubview:navBar];

		
	return self;
}

// Build the Table
- (void)buildTable
{
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	sectionList = [[UISectionList alloc] initWithFrame:CGRectMake(rect.origin.x, 45.0f, rect.size.width, rect.size.height - 90.0f) showSectionIndex:NO];
	[sectionList setDataSource:self];
	[sectionList reloadData];
	table = [sectionList table];
	
	// please show the sectionList even then when there are not more than 20 todos
	[table setShouldHideHeaderInShortLists:NO];
	//Create table to hold all todos
	//table = [[UITable alloc] initWithFrame:CGRectMake(rect.origin.x, 45.0f, rect.size.width, rect.size.height - 45.0f)];
	UITableColumn *col = [[UITableColumn alloc] initWithTitle:@"Todos" identifier:@"todos" width:rect.size.width];
	[table addTableColumn:col];
	[table setSeparatorStyle:1];
	[table setRowHeight:rowHeight];
	[table setDataSource:self];
	[table setDelegate:self];
	[table enableRowDeletion:YES];
	[table reloadData];
//	[table setAllowsReordering:YES];
	
	[self addSubview:sectionList];
}


- (void)reloadTableData
{
	if([[toDoManager getPref:@"rowHeight"] intValue] > 0) {
		rowHeight = [[toDoManager getPref:@"rowHeight"] intValue];
		[table setRowHeight:rowHeight];
	}
	[sectionList reloadData];
	[table reloadData];
}


- (void)toggleEditMode
{
	
	
	if (editMode) 
	{
		editMode = NO;
		//[self allowManualReorder:NO];
		[table reloadData];
		[navBar showLeftButton:@"Edit" withStyle:0 rightButton:@" + " withStyle:0];
	} else {
		editMode = YES;
		//[self allowManualReorder:YES];
		[table reloadData];
		[navBar showLeftButton:@"Done" withStyle:3 rightButton:@" + " withStyle:0];
	}
	
}

- (void)allowManualReorder:(bool)state
{
	int i=0;
	for(i=0;i<[toDoManager numberOfTodos];i++) {
		[[table cellAtRow:i column:0] setShowDisclosureWhenReordering:YES];
		[[table cellAtRow:i column:0] setEnableReordering:state animated:NO];
	
	}
	
}

- (void)createNewToDo
{
	[toDoManager fixOrder];
	
	ToDo *myToDo = [[ToDo alloc] init];
	[toDoManager addToDo:myToDo];
	[toDoManager orderTodosByGroup];
	
	[self reloadTableData];
	
	[toDoManager setCurrentToDo:[toDoManager getNextUnnamed]];
	[td showToDoDetailsWithTransition:1];	
	
}

#pragma mark ----------Delegate Methods-----------

- (void)navigationBar:(UINavigationBar*)bar buttonClicked:(int)button
{
	if(bar == bottomNavBar) {
		// buttom navBar
		[td showToDoPreferencesWithTransition:1];
	}
	else {
		// top navbar
		if(editMode) {
			(button == 0) ? ([self createNewToDo]) : ([self toggleEditMode]);
		}
		else {
			(button == 0) ? ([self createNewToDo]) : ([self toggleEditMode]);
		}
	}
}

- (void)tableRowSelected:(NSNotification *)notification
{
	if(([toDoManager numberOfTodos] == 0) || ([toDoManager numberOfTodos] <= [table selectedRow]) ) {
		return false;
	}
	[toDoManager setCurrentToDo:[table selectedRow]];
	
	if(editMode) {
		[td showToDoDetailsWithTransition:1];
	}
	else {
		// set data
		[toDoManager swapDoneforToDo:[toDoManager getCurrentToDo]];
	}
}

#pragma mark ----------Datasource Methods-----------
-(int)table:(UITable*)table movedRow:(int)row toRow:(int)dest {

	
	int *oldPos = [toDoManager getPositionFromToDo:row];
	int *newPos = [toDoManager getPositionFromToDo:dest];
	
	[toDoManager setPosition:newPos forToDo:row];
	//[toDoManager setPosition:oldPos forToDo:dest];
	
	int i=0;
	if(dest > row) {

		for(i=row+1; i <= dest; i++)
		{

			// push all one row up
			[toDoManager setPosition:([toDoManager getPositionFromToDo:i]-1) forToDo:i];
		}	
	}
	else {

		for(i=dest; i < row; i++)
		{

			// push all one row up
			[toDoManager setPosition:([toDoManager getPositionFromToDo:i]+1) forToDo:i];
		}
	}
	
	
	
	
	
	

	
	[toDoManager writeToFile];
	[toDoManager orderTodosByGroup];
	
	
	[toDoManager fixOrder];
	

	
	return dest;
}
	
- (int)numberOfRowsInTable:(UITable *)table
{
	return [toDoManager numberOfTodos];
}

// Deletion (not implementet yet)
- (BOOL) table:(UITable *) table canDeleteRow:(int) row {
	return YES;
}


- (UITableCell *)table:(UITable *)table cellForRow:(int)row column:(int)col
{	
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	float transparentComponents[4] = {0, 0, 0, 0};
	float grayComponents[4] = {0.55, 0.55, 0.55, 1};
	float redComponents[4] = {0.908, 0.182, 0.159, 1};
	
	//Create description label
	UITextLabel *descriptionLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(55.0f, 3.0f, 210.0f, rowHeight-6)];
	
	[descriptionLabel setText:[toDoManager getDescriptionFromToDo:row]];	
	
	[descriptionLabel setWrapsText:YES];
	[descriptionLabel setBackgroundColor:CGColorCreate(colorSpace, transparentComponents)];
	
	if([toDoManager isToDoExpired:row]) {
		[descriptionLabel setColor:CGColorCreate(colorSpace, redComponents)];
	}
	
	[toDoManager getDaysChecked:row];
	
	UITableCell *cell = [[UITableCell alloc] init];
	UIImageView *img;
	UIImageView *imgIcon;
	float topSpace = (rowHeight - imageHeight) /2;
	// set checkbox!
	if([toDoManager getDoneFromToDo:row] == YES) {
		img = [[UIImageView alloc] initWithFrame:CGRectMake(17.0f, topSpace, 210.0f, 32.0f)];
		[img setImage:checkboxOn];
	}
	else {
		img = [[UIImageView alloc] initWithFrame:CGRectMake(17.0f, topSpace, 210.0f, 32.0f)];
		[img setImage:checkboxOff];
	}
	
	// set icon!
	imgIcon = [[UIImageView alloc] initWithFrame:CGRectMake(5.0f, topSpace+8.0f, 210.0f, 32.0f)];
	switch([toDoManager getPriorityfromToDo:row]) {
		case 1:
		[imgIcon setImage:icon8];
		break;
		case 2:
		[imgIcon setImage:icon7];
		break;
		case 3:
		[imgIcon setImage:icon6];
		break;
		case 4:
		[imgIcon setImage:icon5];
		break;
		case 5:
		[imgIcon setImage:icon4];
		break;
		case 6:
		[imgIcon setImage:icon3];
		break;
		case 7:
		[imgIcon setImage:icon2];
		break;
		case 8:
		[imgIcon setImage:icon1];
		break;
		case 9:
		
		break;

	}
	[cell addSubview:img];
	[cell addSubview:imgIcon];
	[cell addSubview:descriptionLabel];
	
	// edit mode?
	[cell setDisclosureStyle:2];
	(editMode) ? [cell setShowDisclosure:YES animated:NO] : [cell setShowDisclosure:NO animated:NO];
	return cell;
}


#pragma mark ----------SectionList Methods-----------

- (int)numberOfSectionsInSectionList:(UISectionList *)aSectionList {
    return [[toDoManager getPossibleGroups] count];
}
        
- (NSString *)sectionList:(UISectionList *)aSectionList titleForSection:(int)section {
	return [[toDoManager getPossibleGroups] objectAtIndex:(section)];
}       
        
- (int)sectionList:(UISectionList *)aSectionList rowForSection:(int)section {
	return [[[toDoManager getGroupSplits] objectAtIndex:section] intValue];
}

@end